﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sub.TaskPlanningDesk.WebSite.ViewModels.Tasks;
using Sub.TaskPlanningDesk.Model.Objects;
using Sub.TaskPlanningDesk.Model.Services.Projects;

namespace Sub.TaskPlanningDesk.WebSite.Infrastructure.Binders
{
	public class TaskModelBinder : IModelBinder
	{
		private IProjectService _projectService;

		public TaskModelBinder(IProjectService projectService)
		{
			_projectService = projectService;
		}

		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			ValueProviderResult value = bindingContext.ValueProvider.GetValue("Project.ID");
			Project project = _projectService.ByID(Int32.Parse(value.AttemptedValue));

			value = bindingContext.ValueProvider.GetValue("Overview");
			string overview = value.AttemptedValue;

			value = bindingContext.ValueProvider.GetValue("Description");
			string description = value.AttemptedValue;

			value = bindingContext.ValueProvider.GetValue("ID");
			int? taskID = null;
			if (!string.IsNullOrEmpty(value.AttemptedValue))
				taskID = Int32.Parse(value.AttemptedValue);

			Task task = new Task() { Overview = overview, Description = description, ProjectID = project.ID };
			if (taskID.HasValue)
				task.ID = taskID.Value;

			TaskModel model = new TaskModel(project, task, !taskID.HasValue);

			return model;
		}
	}
}